package com.ningxia.water.exception;

import com.ningxia.water.reuslt.Result;
import com.ningxia.water.reuslt.ResultCode;
import com.ningxia.water.reuslt.ResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public Result businessExceptionHandler(HttpServletRequest req, BusinessException e){
        LOGGER.error("发生业务异常！原因是：{}",e.getErrorMsg());
        e.printStackTrace();
        return ResultResponse.getFailResult(e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public Result nullPointerExceptionHandler(HttpServletRequest req, NullPointerException e){
        LOGGER.error("发生空指针异常！原因是:",e.getMessage());
        e.printStackTrace();
        return ResultResponse.getFailResult(ResultCode.BODY_NOT_MATCH);
    }

    /**
     * 处理所有接口数据验证异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e){
        LOGGER.error("发生接口异常！原因是:", e.getMessage());
        e.printStackTrace();
        return ResultResponse.getFailResult(ResultCode.SIGNATURE_NOT_MATCH);
    }

    /**
     * 未知异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest req, Exception e){
        LOGGER.error("未知异常！原因是:",e.getMessage());
        e.printStackTrace();
        return ResultResponse.getFailResult(ResultCode.INTERNAL_SERVER_ERROR);
    }
}
